import {getRequest} from './api'

export const initMenu = (router, store) => {
  if (store.state.routes.length > 0) {
    return
  }
  getRequest('/system/menu/userMenuList').then(resp => {
    if (resp && resp.code === 0 && resp.data) {
      let fmtRoutes = formatRoutes(resp.data)
      router.addRoutes(fmtRoutes)
      store.commit('initRoutes', fmtRoutes)
      store.dispatch('connect')
    }
  })
}
export const formatRoutes = (routes) => {
  let fmRoutes = []
  routes.forEach(router => {
    let {
      path,
      component,
      menuName,
      menuCode,
      menuIcon,
      children
    } = router
    if (children && children instanceof Array) {
      children = formatRoutes(children)
    }
    let fmRouter = {
      path: path,
      menuName: menuName,
      menuIcon: menuIcon,
      menuCode: menuCode,
      children: children,
      component (resolve) {
        if (component.startsWith('Home')) {
          require(['../views/' + component + '.vue'], resolve)
        } else if (component.startsWith('userCenter')) {
          require(['../views/userCenter/' + component + '.vue'], resolve)
        } else if (component.startsWith('system')) {
          require(['../views/system/' + component + '.vue'], resolve)
        }
      }
    }
    fmRoutes.push(fmRouter)
  })
  return fmRoutes
}
